<template>
  <view class="warehouse-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">盘点作业</text>
    </view>

    <!-- 盘点信息 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">盘点信息</text>
      </view>
      <view class="info-form">
        <view class="form-item">
          <text class="form-label">盘点日期</text>
          <picker
            class="form-picker"
            mode="date"
            :value="formData.currentDate"
            @change="handleDateChange"
          >
            <view class="picker-content">
              <text>{{ formData.currentDate }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">当前仓库</text>
          <view class="warehouse-display">{{
            currentWarehouse ? currentWarehouse.warehouseName : "请选择"
          }}</view>
        </view>
      </view>
    </view>

    <!-- 扫码区域 -->
    <view class="material-section">
      <view class="purchase-search-area">
        <view class="scan-input-group">
          <view class="input-row">
            <input
              v-model="searchForm.materialCode"
              class="material-input"
              placeholder="输入物料编码"
              @confirm="scanMaterialCode"
            />
            <button class="scan-btn" @click="scanMaterialCode">扫码</button>
          </view>
          <view class="input-row">
            <input
              v-model="searchForm.materialName"
              class="material-input"
              placeholder="输入物料名称"
              @confirm="searchMaterials"
            />
            <button class="search-btn" @click="searchMaterials">盘盈</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 盘盈新增的物料列表 -->
    <view class="material-section" v-if="materialList.length > 0">
      <view class="section-header">
        <text class="section-title">查询结果</text>
      </view>
      <view class="material-table">
        <view class="table-row header">
          <text class="table-cell">物料名称</text>
          <text class="table-cell">物料编码</text>
          <text class="table-cell">钢种</text>
          <text class="table-cell">规格</text>
        </view>
        <scroll-view class="table-scroll" scroll-y>
          <view
            v-for="item in materialList"
            :key="item.id"
            class="table-row"
            @click="onSelectMaterial(item)"
          >
            <text class="table-cell">{{ item.materialCode }}</text>
            <text class="table-cell">{{ item.materialName }}</text>
            <text class="table-cell">{{ item.steelGradeName }}</text>
            <text class="table-cell">{{ item.specification }}</text>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 盘点明细 -->
    <view class="material-section">
      <view class="section-header">
        <text class="section-title">盘点明细</text>
      </view>

      <view class="material-table" v-if="stockTakingList.length > 0">
        <view class="table-row header">
          <text class="table-cell">物料名称</text>
          <text class="table-cell">物料编码</text>
          <text class="table-cell">钢种</text>
          <text class="table-cell">规格</text>
          <text class="table-cell">账面重量</text>
          <text class="table-cell">账面数量</text>
          <text class="table-cell">实盘重量</text>
          <text class="table-cell">实盘数量</text>
          <text class="table-cell">差异重量</text>
          <text class="table-cell">差异数量</text>
          <text class="table-cell">操作</text>
        </view>
        <scroll-view class="table-scroll" scroll-y>
          <view
            v-for="(item, index) in stockTakingList"
            :key="index"
            class="table-row"
          >
            <text class="table-cell">{{ item.materialName }}</text>
            <text class="table-cell">{{ item.materialCode }}</text>
            <text class="table-cell">{{ item.steelGradeName }}</text>
            <text class="table-cell">{{ item.specification }}</text>
            <text class="table-cell">{{ item.ProdCount || 0 }}</text>
            <text class="table-cell">{{ item.transCount || 0 }}</text>
            <text class="table-cell">
              <input
                v-model.number="item.takingProdCount"
                type="number"
                class="table-input"
                @input="onTakingWeightChange(item)"
                @blur="validateNumberInput(item, 'takingProdCount')"
                placeholder="请输入"
              />
            </text>
            <text class="table-cell">
              <input
                v-model.number="item.takingTransCount"
                type="number"
                class="table-input"
                @input="onTakingQuantityChange(item)"
                @blur="validateNumberInput(item, 'takingTransCount')"
                placeholder="请输入"
              />
            </text>
            <text class="table-cell">
              <input
                :value="
                  (Number(item.takingProdCount) || 0) -
                  (Number(item.ProdCount) || 0)
                "
                type="number"
                class="input-field"
                disabled
              />
            </text>
            <text class="table-cell">
              <input
                :value="
                  (Number(item.takingTransCount) || 0) -
                  (Number(item.transCount) || 0)
                "
                type="number"
                class="input-field"
                disabled
              />
            </text>

            <text class="table-cell">
              <button class="scan-btn" @click="onSubmit(index)">
                称重/确认
              </button>
            </text>
          </view>
        </scroll-view>
      </view>
      <view v-else class="empty-state">
        <uni-icons type="list" size="48" color="#ccc"></uni-icons>
        <text class="empty-text">暂无盘点明细</text>
      </view>
    </view>
    <!-- 统计条 -->
    <view class="statistics-section">
      <view class="stat-item">
        <text class="stat-label">盘点总数量:</text>
        <text class="stat-value">{{ totalQuantity }}件</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">盘点总重量:</text>
        <text class="stat-value">{{ totalWeight }}KG</text>
      </view>
    </view>
  </view>
</template>

<script>
import { queryMaterial } from "@/api/warehouse/stockIn";
import { inventoryApi } from "@/api/warehouse/inventory";
import { submitStockTaking } from "@/api/warehouse/stock-taking";
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
export default {
  name: "StockTaking",
  components: {},
  data() {
    return {
      // 搜索表单
      searchForm: {
        materialCode: "",
        materialName: "",
      },

      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        warehouseCode: "",
        warehouseName: "",
      },
      materialTable: [], // 盘点物料表格数据

      // 当前仓库信息
      currentWarehouse: {
        warehouseCode: "",
        warehouseName: "请选择仓库",
      },
      // 数据定义
      stockTakingNo: "",
      currentDate: "",
      userName: "",
      warehouseList: [],
      selectedWarehouse: null,
      scanCode: "",
      searchKeyword: "",
      materialList: [],
      stockTakingList: [],
      stockTable: [], //库存数据
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 计算属性
    pendingCount() {
      return this.stockTakingList.filter(
        (item) => item.actualQuantity !== item.bookQuantity
      ).length;
    },
    totalWeight() {
      return this.stockTakingList.reduce((total, item) => {
        return total + (Number(item.takingProdCount) || 0);
      }, 0);
    },
    totalQuantity() {
      return this.stockTakingList.reduce((total, item) => {
        return total + (Number(item.takingTransCount) || 0);
      }, 0);
    },
    canSubmit() {
      return (
        this.selectedWarehouse &&
        this.stockTakingList.length > 0 &&
        this.pendingCount > 0
      );
    },
  },
  onLoad() {
    console.log("onLoad");
    this.initData();
  },
  methods: {
    // 初始化数据
    async initData() {
      try {
        // 获取当前仓库信息
        this.loadCurrentWarehouse();
      } catch (error) {
        console.error("初始化数据失败:", error);
        uni.showToast({
          title: "初始化失败",
          icon: "error",
        });
      }
    },

    // 加载当前仓库信息
    loadCurrentWarehouse() {
      const userConfig = this.$store.state.user.userConfig;
      if (userConfig && userConfig.wmName) {
        this.currentWarehouse = {
          warehouseCode: userConfig.wmCode || "DEFAULT",
          warehouseName: userConfig.wmName,
        };
        console.log("currentWarehouse", this.currentWarehouse);
        this.formData.warehouseCode = this.currentWarehouse.warehouseCode;
        this.formData.warehouseName = this.currentWarehouse.warehouseName;
      }
    },
    // 搜索物料（保留原有方法用于其他入库类型）
    async searchMaterials() {
      try {
        let res;

        res = await queryMaterial({
          materialCode: this.materialCode,
          materialName: this.materialName,
          pageNum: 1,
          pageSize: 50,
        });
        if (res.code === 0) {
          this.materialList = (res.data?.list || []).map((item) => ({
            ...item,
          }));
          //console.log("materialList", this.materialList);
        }
      } catch (error) {
        console.error("搜索物料失败:", error);
      }
    },

    // 查询库存
    async scanMaterialCode() {
      if (this.loading) return;

      try {
        console.log("searchForm", this.searchForm);
        console.log("currentWarehouse", this.currentWarehouse);
        this.loading = true;

        const params = {
          pageNum: 1,
          pageSize: 50,
          warehouseName: this.currentWarehouse.warehouseName,
          materialCode: this.searchForm.materialCode,
          materialName: this.searchForm.materialName,
        };

        const response = await inventoryApi.getStockReal(params);

        if (response.code === 0) {
          this.stockTable = (response.data.list || []).map((item) => ({
            ...item,
          }));
          //将stockTable中的数据增加到stockTakingList中
          this.stockTable.forEach((item) => {
            const existingItem = this.stockTakingList.find(
              (i) => i.materialCode === item.materialCode
            );
            if (existingItem) {
              existingItem.actualQuantity = item.actualQuantity || 0;
              existingItem.unitPrice = item.unitPrice || 0;
            } else {
              this.stockTakingList.push({
                ...item,
                actualQuantity: item.actualQuantity || 0,
                unitPrice: item.unitPrice || 0,
                differenceQuantity: item.actualQuantity || 0,
                ProdCount: item.ProdCount || 0,
                transCount: item.transCount || 0,
                takingProdCount: item.takingProdCount || 0,
                takingTransCount: item.takingTransCount || 0,
                differenceAmount: item.differenceAmount || 0,
              });
            }
          });
          if (this.stockTable.length === 0) {
            uni.showToast({
              title: "未查询到库存数据，建议盘盈！",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.msg || "查询失败",
            icon: "error",
          });
        }
      } catch (error) {
        console.error("查询库存失败:", error);
        uni.showToast({
          title: "查询失败",
          icon: "error",
        });
      } finally {
        this.loading = false;
      }
    },
    // 方法定义
    generateStockTakingNo() {
      const date = new Date();
      const dateStr =
        date.getFullYear().toString() +
        (date.getMonth() + 1).toString().padStart(2, "0") +
        date.getDate().toString().padStart(2, "0");
      const randomStr = Math.random().toString(36).substr(2, 6).toUpperCase();
      return `PD${dateStr}${randomStr}`;
    },

    addToStockTakingList(material) {
      const existingItem = this.stockTakingList.find(
        (item) => item.materialCode === material.materialCode
      );
      if (existingItem) {
        uni.showToast({
          title: "该物料已在盘点列表中",
          icon: "none",
        });
        return;
      }

      const newItem = {
        materialId: material.id,
        materialCode: material.materialCode,
        materialName: material.materialName,
        spec: material.specification,
        steelGradeName: material.steelGradeName,
        unit: material.unit,
        specification: material.specification,
        ProdCount: 0,
        transCount: 0,
        takingProdCount: 0,
        takingTransCount: 0,
        differenceQuantity: 0,
        differenceAmount: 0,
        unitPrice: 0,
      };

      console.log("添加新物料到盘点列表:", newItem);
      this.stockTakingList.push(newItem);
      console.log("当前盘点列表:", this.stockTakingList);
    },

    onQuantityChange(item) {
      item.differenceQuantity =
        (item.actualQuantity || 0) - (item.bookQuantity || 0);
      item.differenceAmount = item.differenceQuantity * (item.unitPrice || 0);
    },

    onPriceChange(item) {
      item.differenceAmount =
        (item.differenceQuantity || 0) * (item.unitPrice || 0);
    },

    // 实盘重量变化处理
    onTakingWeightChange(item) {
      // 确保输入值为有效数字
      if (!this.validateNumber(item.takingProdCount)) {
        item.takingProdCount = 0;
      }
      // 更新差异重量（实盘重量 - 账面重量）
      item.differenceQuantity =
        (Number(item.takingProdCount) || 0) - (Number(item.ProdCount) || 0);
      // 更新差异金额
      this.onPriceChange(item);
    },

    // 实盘数量变化处理
    onTakingQuantityChange(item) {
      // 确保输入值为有效数字
      if (!this.validateNumber(item.takingTransCount)) {
        item.takingTransCount = 0;
      }
    },

    // 数字输入校验
    validateNumberInput(item, field) {
      const value = item[field];
      if (!this.validateNumber(value)) {
        uni.showToast({
          title: "请输入有效的数字",
          icon: "none",
        });
        item[field] = 0;
      }
    },

    onDeleteItem(index) {
      uni.showModal({
        title: "提示",
        content: "确定要删除这条盘点明细吗？",
        success: (res) => {
          if (res.confirm) {
            this.stockTakingList.splice(index, 1);
          }
        },
      });
    },

    validateNumber(value) {
      return !isNaN(value) && value >= 0;
    },

    onReset() {
      uni.showModal({
        title: "提示",
        content: "确定要重置所有数据吗？",
        success: (res) => {
          if (res.confirm) {
            this.stockTakingList.splice(0);
            this.materialList = [];
            this.scanCode = "";
            this.searchKeyword = "";
          }
        },
      });
    },
    onSelectMaterial(material) {
      //console.log("material", material);
      this.addToStockTakingList(material);
      this.materialList = [];
      this.searchKeyword = "";
    },
    // 处理日期变更
    handleDateChange(e) {
      this.formData.outDate = e.detail.value;
    },

    onSubmit(rowIndex) {
      // 如果传入了行索引，则针对单行数据提交，否则提交所有数据
      const itemsToSubmit =
        rowIndex !== undefined
          ? [this.stockTakingList[rowIndex]]
          : this.stockTakingList;

      // 验证数据
      for (let item of itemsToSubmit) {
        if (!this.validateNumber(item.takingProdCount)) {
          uni.showToast({
            title: "实盘重量必须为有效数字",
            icon: "none",
          });
          return;
        }
        if (!this.validateNumber(item.takingTransCount)) {
          uni.showToast({
            title: "实盘数量必须为有效数字",
            icon: "none",
          });
          return;
        }
        if (!this.validateNumber(item.unitPrice)) {
          uni.showToast({
            title: "单价必须为有效数字",
            icon: "none",
          });
          return;
        }
      }

      const confirmText =
        rowIndex !== undefined
          ? `确认提交第${rowIndex + 1}行物料${
              itemsToSubmit[0].materialName
            }的盘点数据？`
          : `共${itemsToSubmit.length}条盘点明细，待提交${this.pendingCount}条，是否确认提交？`;

      uni.showModal({
        title: "确认提交",
        content: confirmText,
        success: async (res) => {
          if (res.confirm) {
            try {
              await submitStockTaking(itemsToSubmit, this.selectedWarehouse.id);
              uni.showToast({
                title: "提交成功",
                icon: "success",
              });

              // 如果是单行提交，移除已提交的行
              if (rowIndex !== undefined) {
                this.stockTakingList.splice(rowIndex, 1);
              } else {
                // 如果是全部提交，清空列表
                this.stockTakingList.splice(0);
              }
            } catch (error) {
              uni.showToast({
                title: "提交失败",
                icon: "none",
              });
            }
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/smart/scss/create.scss";
</style>
